package com.wolfpire.system.common.util;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class BeanUtils {
	
	private static final Logger logger = Logger.getLogger(BeanUtils.class);
	
	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
	private static final DateFormat HOUR_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private static final DateFormat TIME_FROMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static BeanUtilsBean beanUtilsBean;
	public static ConvertUtilsBean convertUtilsBean;
	
	static {
		convertUtilsBean = new ConvertUtilsBean();
		convertUtilsBean.register(new Converter(){

			@SuppressWarnings("rawtypes")
			public Object convert(Class arg0, Object arg1) {
				
				if (arg1 instanceof Date) {
					Date date = (Date) arg1;
					return date;
				} else {
					String p = (String)arg1;

					if(p== null || p.trim().length()==0){
						return null;
					}
					p = p.trim();
					try{
						if(p.length() == 10){
							return DATE_FORMAT.parse(p);
						}else if(p.length() == 16){
							return HOUR_FORMAT.parse(p);
						}else if(p.length() == 19){
							return TIME_FROMAT.parse(p);
						}else{
							return null;
						}
					}catch(Exception e){
						logger.error("把"+arg1+"转换成时间类型出错", e);
						return null;
					}
				}
				
				
			}
			
		}, Date.class);
		
		convertUtilsBean.register(new Converter() {
			
			@SuppressWarnings("rawtypes")
			
			public Object convert(Class arg0, Object arg1) {
				
				BigDecimalConverter converter = new BigDecimalConverter();
				
				if(StringUtils.isNotBlank(arg1.toString())){
					return converter.convert(BigDecimal.class, arg1);
				}else{
					return new BigDecimal(0);
				}
				
			}
		}, BigDecimal.class);

		beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
	}

}
